package com.nic.view.widget;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.nic.view.R;
import com.nic.view.ViewConfig;
import com.nic.view.activity.PhotoPreviewActivity;
import com.nic.view.adapter.TakePhotoAdapter;
import com.nic.view.util.JLog;
import com.nic.view.util.PhotoUtils;

import java.io.File;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 图片采集上传
 * Created by Administrator on 2018/7/19.
 */

public class TakePhotoView extends LinearLayout implements AdapterView.OnItemClickListener {

    /**
     * 选择图片的返回码
     */
//    private int requestTakeImgCode = 233;
//    private int requestTakeSourCode = 234;
//
//    public void setRequestTakeImgCode(int requestTakeImgCode) {
//        this.requestTakeImgCode = requestTakeImgCode;
//    }
//
//    public void setRequestTakeSourCode(int requestTakeSourCode) {
//        this.requestTakeSourCode = requestTakeSourCode;
//    }

    /**
     * 选择图片的返回码
     */
    private int requestCode = 233;
    private MyGridView uploadGridView;


    /**
     * @param isPreview       是否预览
     * @param isAddMultiPhoto 是否添加多张
     */
    public void setTakePhotoConfig(boolean isPreview, boolean isAddMultiPhoto) {
        adapter.setPreview(isPreview);
        adapter.setIsAddMultiPhoto(isAddMultiPhoto);
        adapter.setList(null);//初始化加号图片

    }

    /**
     * 图片上传Adapter
     */
    private TakePhotoAdapter adapter;
    private SelectPicDialog selectPicDialog;
    //    private UploadFileRequest mUploadFileUtil;
    private String imageFilePath;
    private boolean isPreview;

    public TakePhotoView(Context context) {
        super(context);
    }

    public List<String> getDataList() {
        return adapter.getList();
    }


    public void setRequestCode(int code) {
        this.requestCode = code;
    }


    public String getPaths() {
        if (getDataList().isEmpty()) {
            return "";
        }
        return TextUtils.join(",", getDataList());
    }

    public TakePhotoView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public TakePhotoView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public TakePhotoView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context);
    }

    private void init(Context context) {
        LayoutInflater.from(context).inflate(R.layout.fragment_choose, this);
        uploadGridView = (MyGridView) findViewById(R.id.grid_upload_pictures);
        adapter = new TakePhotoAdapter(context);
        uploadGridView.setAdapter(adapter);
        setTakePhotoConfig(false, true);
        uploadGridView.setOnItemClickListener(this);
//        mUploadFileUtil = new UploadFileRequest((Activity) context);
    }

    private void setUrlList(String urls) {
        PhotoUtils.savePhotoToLoc(urls, new PhotoUtils.OnLoadingListener() {
            @Override
            public void onLoadingUpdate(String locPath) {
                if (!TextUtils.isEmpty(locPath)) {
                    adapter.addLast(locPath);
                }
            }
        });
    }

//    public void setHint(String hint) {
//        mUploadFileUtil.setHint(hint);
//    }

//    /**
//     * @param hint
//     * @param lis
//     * @param requestCode
//     */
//    public void setOnUploadListener(String hint, AbUploadFile.OnResultUploadListener lis, int requestCode) {
//        this.requestCode = requestCode;
//        mUploadFileUtil.setHint(hint);
//        mUploadFileUtil.setOnResultUploadListener(lis);
//    }

//    /**
//     * @param hint
//     * @param lis
//     */
//    public void setOnUploadListener(String hint, AbUploadFile.OnResultUploadListener lis) {
//        mUploadFileUtil.setHint(hint);
//        mUploadFileUtil.setOnResultUploadListener(lis);
//    }

//    /**
//     * @param lis
//     */
//    public void setOnUploadListener(AbUploadFile.OnResultUploadListener lis) {
//        mUploadFileUtil.setHint("图像资料");
//        mUploadFileUtil.setOnResultUploadListener(lis);
//    }

//    /**
//     * 调用上传请求
//     */
//    public void request() {
//        mUploadFileUtil.setImagePaths(getDataList());
//        mUploadFileUtil.uploadImgs();
//    }

    private void jumpPreview() {

        Intent intent = new Intent(getContext(), PhotoPreviewActivity.class);
        intent.putExtra(PhotoPreviewActivity.LIST, (Serializable) getDataList());
        getContext().startActivity(intent);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
        String url = (String) parent.getItemAtPosition(position);
        if (isPreview) {
            jumpPreview();
            return;
        }
        if (adapter.getCount() - 1 == position && TextUtils.isEmpty(url)) { // 添加图片
            showPicturePopupWindow(view);//PopupWindow形式
        } else {
            jumpPreview();
        }
    }

    /**
     * 拍照或从图库选择图片(PopupWindow形式)
     */
    public void showPicturePopupWindow(View groupView) {
        selectPicDialog = new SelectPicDialog(getContext(), new OnClickListener() {
            @Override
            public void onClick(View v) {
                selectPicDialog.dismiss();
                int i = v.getId();
                if (i == R.id.takePhotoBtn) {
                    takePhoto();

                } else if (i == R.id.pickPhotoBtn) {
                    pickPhoto();

                } else if (i == R.id.cancelBtn) {
                } else {
                }
            }
        });

        selectPicDialog.setCurrentType(0);
        selectPicDialog.show();
//        if (groupView == null) {
//            selectPicDialog.showAtLocation(this, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
//        } else {
//            menuWindow.showAtLocation(groupView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
//        }
    }

    /**
     * 当前选择的图片的路径
     */
    public String mImagePath;

    /**
     * 拍照获取图片
     */
    private void takePhoto() {
        // 执行拍照前，应该先判断SD卡是否存在
//        String SDState = Environment.getExternalStorageState();
//        if (SDState.equals(Environment.MEDIA_MOUNTED)) {
//            /**
//             * 通过指定图片存储路径，解决部分机型onActivityResult回调 data返回为null的情况
//             */
//            //获取与应用相关联的路径
//            String imageFilePath = getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath();
//            startTakePhoto(imageFilePath);
//        } else {
//            String imageFilePath = getContext().getFilesDir().getAbsolutePath();
//            startTakePhoto(imageFilePath);
//        }
        startTakePhoto();
    }

    /**
     * 请求拍照权限
     */
    private Uri autoObtainCameraPermission() {


        //有权限直接调用系统相机拍照
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);
            //根据当前时间生成图片的名称
            String timestamp = "/" + formatter.format(new Date()) + ".jpg";
            String storagePath = Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                    .getAbsolutePath() + File.separator + getContext().getString(R.string.provider_path) + File.separator + "photo";
            File storageDir = new File(storagePath);
            if (!storageDir.exists()) {
                storageDir.mkdirs();
            }
            File imageFile = new File(storageDir, timestamp);// 通过路径创建保存文件
            mImagePath = imageFile.getAbsolutePath();
            //通过FileProvider创建一个content类型的Uri
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                return ViewConfig.getFileProviderA7(getContext(), imageFile);
            }
            return Uri.fromFile(imageFile);
        } else {
            Toast.makeText(getContext(), "设备没有SD卡！", Toast.LENGTH_SHORT).show();
        }
        return null;
    }

    /**
     * 拍照选择图片
     */
    private void startTakePhoto() {
        Uri imageFileUri = autoObtainCameraPermission(); // Uri.fromFile(imageFile);// 获取文件的Uri
        if (imageFileUri == null) {
            return;
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri);// 告诉相机拍摄完毕输出图片到指定的Uri
        ((Activity) getContext()).startActivityForResult(intent, requestCode);
    }

    /***
     * 从相册中取图片
     */
    private void pickPhoto() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        ((Activity) getContext()).startActivityForResult(intent, requestCode);
    }


    /**
     * Activity返回
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK && this.requestCode == requestCode) {
            if (data != null && data.getData() != null) {//相册
                mImagePath = PhotoUtils.getImageAbsolutePath((Activity) getContext(), Uri.parse(Uri.decode(data.getDataString())));
                JLog.e("->" + mImagePath);
                adapter.addLast(mImagePath);
            } else {//拍照
                JLog.e("->" + mImagePath);
                //                mImagePath = ImageUtils.amendRotatePhoto(mImagePath, getContext());
                adapter.addLast(mImagePath);
            }
        }
    }

    /**
     * 预览网络图片
     *
     * @param urls      url1,url2,..
     * @param isPreview 仅预览
     */
    public void setPreviewUrls(String urls, boolean isPreview) {
        this.isPreview = isPreview;
        if (TextUtils.isEmpty(urls)) {
            return;
        }
        setTakePhotoConfig(isPreview, true);
        setUrlList(urls);
    }

    /**
     * 预览网络图片
     *
     * @param url       url
     * @param isPreview 仅预览
     */
    public void setSinglePreviewUrls(String url, boolean isPreview) {
        this.isPreview = isPreview;
        if (!TextUtils.isEmpty(url)) {
            return;
        }
        setTakePhotoConfig(isPreview, false);
        setUrlList(url);
    }
}
